package com.kuiandjie.web;


import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;
import com.kuiandjie.entity.Employee;
import com.kuiandjie.entity.Idea;
import com.kuiandjie.entity.Log;
import com.kuiandjie.entity.Project;
import com.kuiandjie.service.IdeaService;
import com.kuiandjie.service.LogService;
import com.kuiandjie.util.DateUtil;

public class NewIdeaServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		Project curp = (Project) session.getAttribute("curp");
		String type = request.getMethod();
		if(curp != null) {
			if("GET".equals(type)) {
				request.getRequestDispatcher("WEB-INF/views/newidea.jsp").forward(request, response);
			} else {
				Employee e = (Employee) session.getAttribute("employee");
				String title = request.getParameter("title");
				String content = request.getParameter("content");
				
				Idea i = new Idea();
				i.setContent(content);
				i.setCreatetime(DateUtil.getNow());
				i.setEmployeeId(e.getId());
				i.setProjectId(curp.getId());
				i.setTitle(title);
				
				int ideaId = new IdeaService().insertIdea(i);
				
				if(ideaId != -1) {
					Log log = new Log();
					log.setDesc("有了一个新想法<a href='idea.jspx?id=" + ideaId + "'>" + title + "</a>");
					log.setEmployeeId(e.getId());
					log.setProjectId(curp.getId());
					log.setTime(DateUtil.getNow());
					log.setName(e.getName());
					log.setPic(e.getPic());
					
					LogService ls = new LogService();
					ls.inserLog(log);
					
					request.setAttribute("msg", new Gson().toJson(log));
					request.getRequestDispatcher("msgflow.jspx").include(request, response);
				}
				
				response.setContentType("text/html");
				PrintWriter out = response.getWriter();
				
				out.print("10001");
				out.flush();
				out.close();
			}
		}
	}
}
